/*******************************************************************************
 * Copyright 2011 Andrea Guitto
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.andreaguitto.mobile.android.framework.base.object.task;

import java.io.File;
import java.io.FileOutputStream;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.andreaguitto.mobile.android.framework.base.object.activity.AGActivity;

public class AGAsyncFileSaveTask extends AGAsyncWorkTask<byte[], String, String> {
	
	public AGAsyncFileSaveTask(AGActivity activity, ProgressDialog progressDialog) {
		super(activity, progressDialog);
	}

	private boolean externalStorage;
	public boolean isExternalStorage() {	return externalStorage; }
	public void setExternalStorage(boolean externalStorage) {	this.externalStorage = externalStorage;	}

	private String filepath;
	public String getFilepath() {	return filepath;	}
	/**
	 * Set filepath with ended with '/' like '/sdcard/my/yours/'
	 * 
	 * @param filepath
	 */
	public void setFilepath(String filepath) {	this.filepath = filepath;	}
	
	private String filename;	
	public String getFilename() {	return filename;	}
	public void setFilename(String filename) {	this.filename = filename;	}
	

	@Override
	protected String doInBackground(byte[]... fileBytesArrays) {
		
		for (int i=0; i< fileBytesArrays.length; i++){
			File file = null;
			if(externalStorage){
				if(fileBytesArrays.length >0)
					file=new File(Environment.getExternalStorageDirectory(),filepath+filename+"_"+i);
				else
					file=new File(Environment.getExternalStorageDirectory(),filepath+filename);
				
				if (file.exists()) {
					file.delete();
				}
			}
			
			if(file!=null){
				try {
					FileOutputStream fos;
					if(externalStorage)	
						fos=new FileOutputStream(file.getPath());
					else
						fos = activity.openFileOutput(filename, Context.MODE_PRIVATE);
					
					fos.write(fileBytesArrays[i]);
					fos.close();
				}
				catch (java.io.IOException e) {
					Log.d(getLogTag(), e.getStackTrace().toString());
				}
			}
		}
		return(externalStorage?filepath+filename:filename);
	}
}
